package kr.saeildamil.androidforstudy2.ch25;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;

import kr.saeildamil.androidforstudy2.R;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class FileIO extends Activity {
	EditText mEdit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch25_fileio);

		mEdit = (EditText) findViewById(R.id.edittext);

	}

	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.save:
			FileOutputStream fos;
			try {
				fos = openFileOutput("test.txt", Context.MODE_WORLD_READABLE);
				String str = "Android File IO TEST";
				fos.write(str.getBytes());
				fos.close();
				mEdit.setText("File, Write Successfully");
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.load:
			try {
				FileInputStream fis = openFileInput("test.txt");
				byte[] data = new byte[fis.available()];
				fis.read(data);
				mEdit.setText(new String(data));
			} catch (FileNotFoundException e) {
				mEdit.setText("File not found.");
			} catch (Exception e) {
			}
			break;
		case R.id.loadres:
			try {
				InputStream fres = getResources()
						.openRawResource(R.raw.restext);
				byte[] data = new byte[fres.available()];
				fres.read(data);
				fres.close();
				mEdit.setText(new String(data));
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case R.id.delete:
			if(deleteFile("test.txt")){
				mEdit.setText("File, Delete Successfully");
			}else{
				mEdit.setText("Delete Failed.");
			}
			break;
		}
	}
}
